package app.caihan.wanandroid.model.api

import app.caihan.scframe.api.retrofit2.BaseRetrofitClient
import app.caihan.scframe.api.retrofit2.interceptor.LoggingInterceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit

/**
 * 玩安卓-网络请求客户端
 *
 * @author Seven-C
 * @date 2020/8/10
 */
object WanRetrofitClient : BaseRetrofitClient() {

    val apiService by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
        getService(WanService::class.java, WanService.BASE_URL)
    }

    /**
     * 实现重写父类的setHttpClientBuilder方法，
     * 在这里可以添加拦截器，可以对 OkHttpClient.Builder 做任意操作
     */
    override fun setHttpClientBuilder(builder: OkHttpClient.Builder): OkHttpClient.Builder {
        return builder.apply {
            //超时时间 连接、读、写
            connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS)
            writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS)
            callTimeout(CALL_TIME_OUT, TimeUnit.SECONDS)
            //添加Cookies自动持久化
            cookieJar(cookieJar)
            //添加公共heads 注意要设置在日志拦截器之前，不然Log中会不显示head信息
            addInterceptor(MyHeadInterceptor())
            //日志拦截器
            addInterceptor(LoggingInterceptor())
        }
    }

    /**
     * 实现重写父类的setRetrofitBuilder方法，
     * 在这里可以对Retrofit.Builder做任意操作，比如添加GSON解析器，protobuf等
     */
    override fun setRetrofitBuilder(builder: Retrofit.Builder): Retrofit.Builder {
        return builder.apply {
            addConverterFactory(GsonConverterFactory.create())
            addConverterFactory(ScalarsConverterFactory.create())
        }
    }
}